#include "dlgaddlabel.h"
#include "ui_dlgaddlabel.h"

#include <QMessageBox>

DlgAddLabel::DlgAddLabel(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DlgAddLabel)
{
    ui->setupUi(this);
    //使每次弹窗都在最前面
    setWindowFlag(Qt::WindowStaysOnTopHint);
}

DlgAddLabel::~DlgAddLabel()
{
    delete ui;
}

void DlgAddLabel::showLabel(QString strLabel)
{
    ui->listWidgetLabel->clear();
    m_labelList.clear();
    if (strLabel.isEmpty())
    {
        ui->ptnReduceLabel->setEnabled(false);
    }
    else
    {
        ui->ptnReduceLabel->setEnabled(true);
        QStringList labelList = strLabel.split(";");
        for(QString label : labelList)
        {
            if (label.length()>0)
            {
                label = label.trimmed();
                if (!m_labelList.contains(label))
                {
                    m_labelList.append(label);
                    QListWidgetItem *item = new QListWidgetItem;
                    item->setText(label);
                    ui->listWidgetLabel->addItem(item);
                    ui->listWidgetLabel->setCurrentItem(item); //默认选中刚添加的行
                }
            }
        }
    }
}

void DlgAddLabel::on_ptnAddLabel_clicked()
{
    QString labelStr = ui->lineEditAddLabel->text();
    if (labelStr.isEmpty())
    {
        QMessageBox::critical(this,"错误",QString("添加标签为空"));
        return;
    }

    //如果标签不为空，设置移除按钮为可用
    ui->ptnReduceLabel->setEnabled(true);
    ui->lineEditAddLabel->clear();

    QStringList labelList = labelStr.split(";");
    for (QString label : labelList)
    {
        if (label.length()>0)
        {
            label = label.trimmed();
            if (!m_labelList.contains(label))
            {
                m_labelList.append(label);
                QListWidgetItem *item = new QListWidgetItem;
                item->setText(label);
                ui->listWidgetLabel->addItem(item);
                ui->listWidgetLabel->setCurrentItem(item); //默认选中刚添加的行
            }
        }
    }

    //更新数据
    emit sendLabelData(m_labelList);
}


void DlgAddLabel::on_ptnReduceLabel_clicked()
{
    QListWidgetItem *item = ui->listWidgetLabel->currentItem();
    QString delLabel = item->text();
    //从全局变量m_labelList中移除
    m_labelList.removeAt(m_labelList.indexOf(delLabel));

    //删除listWidget对应的项
    delete item;

    //如果listWidget清空了，设置删除按钮为不可用
    if (ui->listWidgetLabel->count() == 0)
    {
        ui->ptnReduceLabel->setEnabled(false);
        ui->ptnAddLabel->setFocus();
    }

    //更新数据
    emit sendLabelData(m_labelList);
}
